<template>
  <BasicModal :title="title" :width="700" v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
  <PreviewCodeModel @register="previewCodeModel" />
</template>


<script lang="ts" setup>
import {computed, ref, unref} from 'vue'

import {BasicForm, useForm} from '/@/components/Form/index'
import {BasicModal, useModal, useModalInner} from '/@/components/Modal'
import PreviewCodeModel from './PreviewCodeModel.vue';
import {genCode, getGenInfo} from '../codeGen.api'
import {genCodeFormSchema} from '../codeGen.data'
import {listTemplateGroup} from '../../templateGroup/templateGroup.api';
import {listByGroupId} from '../../template/template.api';
import {useMessage} from '/@/hooks/web/useMessage'

const { createMessage } = useMessage()
const emit = defineEmits(['success', 'register'])
const props = defineProps({
  rootTreeData: { type: Array, default: () => [] },
})
const isUpdate = ref<boolean>(false)
// 当前的弹窗数据
// const model = ref<object>({})
const title = computed(() => '生成代码')

//注册表单
const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  schemas: genCodeFormSchema,
  showActionButtonGroup: false,
  wrapperCol: { lg: 24, md: 24 }
})

const [previewCodeModel, { openModal: openPreviewCodeModel }] = useModal();

// 注册弹窗
const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
  await resetFields()
  const { id } = unref(data)
  // 获取所有模板组
  const templateGropp = await listTemplateGroup({})
  updateSchema([
    {
      field: 'templateGroupId',
      componentProps: ({ formModel, formActionType }) => {
        return {
          optionFilterProp: "label",
          showSearch: true,
          options: templateGropp,
          onChange: async (templateGroupId: any) => {
            const { updateSchema } = formActionType;
            formModel.templateIds = undefined; //  reset value
            if (!templateGroupId) {
              return
            }
            updateFromTemplateIds(templateGroupId, updateSchema)
          }
        };
      },
    }
  ])

  const templateGroupId = templateGropp.length > 0 ? templateGropp[0].id : undefined
  updateFromTemplateIds(templateGroupId, updateSchema)

  // 获取生成信息
  const genInfo = await getGenInfo(id)

  // 赋默认值
  await setFieldsValue({ genTableId: id, ...genInfo })
})

const updateFromTemplateIds = async (templateGroupId, updateSchema) => {
  const templateList = await listByGroupId({ groupId: templateGroupId });

  updateSchema({
    field: 'templateIds',
    componentProps: {
      optionFilterProp: "label",
      showSearch: true,
      options: templateList,
    },
  });

  await setFieldsValue({ templateGroupId, templateIds: templateList.map(e => e.id) })
}

// 提交事件
async function handleOk() {
  try {
    setModalProps({ confirmLoading: true })
    let values = await validate()
    console.log("gen code from: ", values)
    const codeList = await genCode(values)
    openPreviewCodeModel(true, { list: codeList })
    //提交表单
    // await saveOrUpdateDepart(values, isUpdate.value)
    //关闭弹窗
    closeModal()
    //刷新列表
    emit('success')
  } finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>
